package com.pipe.protocol.login;

import com.pipe.util.IntegerConveter;
import com.pipe.util.MysqlProtocolUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

/**
 * @author Kiven
 */
public class HandshakeResponsePacket {
    private int clientFlag;
    private int maxPacketSize;
    private short characterSet;
    private byte[] filler;
    private byte[] userName;

    private byte authResponseLength;
    private byte[] authResponse;

    /**暂时不启用对database的支持*/
    private byte[] database;
    private byte[] clientPluginName;

    public HandshakeResponsePacket(short characterSet, String userName, byte[] authResponse, String database, String clientPluginName) {
        this.clientFlag = CapabilitiesFlags.CLIENT_PROTOCOL_41 | CapabilitiesFlags.CLIENT_PLUGIN_AUTH | CapabilitiesFlags.CLIENT_SERCURE_CONNECTION | CapabilitiesFlags.CLIENT_CONNECT_WITH_DB;
        this.maxPacketSize = 2048;
        this.characterSet = characterSet;
        this.filler = new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        this.userName = MysqlProtocolUtil.string2arrZeroTail(userName);
        this.authResponseLength = (byte) authResponse.length;
        this.authResponse = authResponse;
        this.database = MysqlProtocolUtil.string2arrZeroTail(database);
        this.clientPluginName = MysqlProtocolUtil.string2arrZeroTail(clientPluginName);
    }

    public ByteBuf toBytebuf() {
        byte[] cfArr = IntegerConveter.getByte4Array(clientFlag);
        byte[] mpSizeArr = IntegerConveter.getByte4Array(maxPacketSize);

        ByteBuf byteBuf = Unpooled.directBuffer(cfArr.length + mpSizeArr.length + 1 + filler.length + userName.length + 1 + authResponse.length + database.length + clientPluginName.length);

        byteBuf.writeBytes(cfArr);
        byteBuf.writeBytes(mpSizeArr);
        byteBuf.writeByte((byte) characterSet);
        byteBuf.writeBytes(filler);
        byteBuf.writeBytes(userName);
        byteBuf.writeByte(authResponseLength);
        byteBuf.writeBytes(authResponse);
        byteBuf.writeBytes(database);
        byteBuf.writeBytes(clientPluginName);

        return byteBuf;

    }
}